/**
 * 统一进度管理系统
 * 提供智能缓存、错误处理和降级策略的进度管理接口
 */

import { ref, reactive, computed } from 'vue'
import { 
  getLessonProgress, 
  updateReadingProgress, 
  updateVocabularyProgress,
  updateEssayProgress 
} from '@/api/userProgress'
// 注意：getLessonDetails, getQuizProgress, saveQuizProgress 已在上面从 @/api/userProgress 导入

// 全局进度缓存
const progressCache = reactive(new Map())
const cacheTimestamps = reactive(new Map())
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

// 错误状态管理
const errors = reactive(new Map())
const retryAttempts = reactive(new Map())
const MAX_RETRY_ATTEMPTS = 3

/**
 * 统一进度管理Hook
 * @param {string} moduleType - 模块类型 ('lesson', 'quiz', 'vocabulary', 'essay')
 * @returns {Object} 进度管理接口
 */
export function useProgress(moduleType = 'lesson') {
  const isLoading = ref(false)
  const error = ref(null)
  const progressData = ref(null)

  /**
   * 检查缓存是否有效
   * @param {string} key - 缓存键
   * @returns {boolean}
   */
  const isCacheValid = (key) => {
    if (!progressCache.has(key) || !cacheTimestamps.has(key)) {
      return false
    }
    const timestamp = cacheTimestamps.get(key)
    return Date.now() - timestamp < CACHE_DURATION
  }

  /**
   * 设置缓存
   * @param {string} key - 缓存键
   * @param {any} data - 数据
   */
  const setCache = (key, data) => {
    progressCache.set(key, data)
    cacheTimestamps.set(key, Date.now())
  }

  /**
   * 获取缓存
   * @param {string} key - 缓存键
   * @returns {any}
   */
  const getCache = (key) => {
    return progressCache.get(key)
  }

  /**
   * 清除特定缓存
   * @param {string} key - 缓存键
   */
  const clearCache = (key) => {
    progressCache.delete(key)
    cacheTimestamps.delete(key)
    errors.delete(key)
    retryAttempts.delete(key)
  }

  /**
   * 清除所有缓存
   */
  const clearAllCache = () => {
    progressCache.clear()
    cacheTimestamps.clear()
    errors.clear()
    retryAttempts.clear()
  }

  /**
   * 错误处理和重试逻辑
   * @param {string} key - 缓存键
   * @param {Function} apiCall - API调用函数
   * @param {any} fallbackData - 降级数据
   * @returns {Promise<any>}
   */
  const handleApiCall = async (key, apiCall, fallbackData = null) => {
    const currentRetries = retryAttempts.get(key) || 0
    
    try {
      const response = await apiCall()
      
      // 重置错误状态
      errors.delete(key)
      retryAttempts.delete(key)
      
      if (response.code === 0 && response.data) {
        setCache(key, response.data)
        return response.data
      } else {
        throw new Error(response.msg || 'API返回错误')
      }
    } catch (err) {
      console.error(`API调用失败 [${key}]:`, err)
      errors.set(key, err.message)
      
      // 重试逻辑
      if (currentRetries < MAX_RETRY_ATTEMPTS) {
        retryAttempts.set(key, currentRetries + 1)
        console.log(`重试第 ${currentRetries + 1} 次: ${key}`)
        
        // 延迟重试
        await new Promise(resolve => setTimeout(resolve, 1000 * currentRetries))
        return handleApiCall(key, apiCall, fallbackData)
      }
      
      // 使用降级策略
      if (fallbackData) {
        console.warn(`使用降级数据 [${key}]:`, fallbackData)
        return fallbackData
      }
      
      throw err
    }
  }

  /**
   * 获取课程进度
   * @param {string} lessonId - 课程ID
   * @returns {Promise<Object>}
   */
  const getLessonProgressData = async (lessonId) => {
    const cacheKey = `lesson_progress_${lessonId}`
    
    // 检查缓存
    if (isCacheValid(cacheKey)) {
      progressData.value = getCache(cacheKey)
      return progressData.value
    }

    isLoading.value = true
    error.value = null

    try {
      const fallbackData = {
        lesson_id: lessonId,
        progress: 0,
        is_completed: false,
        vocabulary_progress: 0,
        quiz_progress: 0,
        essay_progress: 0,
        total_words: 0,
        learned_words: 0
      }

      const data = await handleApiCall(
        cacheKey,
        () => getLessonProgress(lessonId),
        fallbackData
      )

      progressData.value = data
      return data
    } catch (err) {
      error.value = err.message
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 获取课程详情
   * @param {string} lessonId - 课程ID
   * @returns {Promise<Object>}
   */
  const getLessonDetailsData = async (lessonId) => {
    const cacheKey = `lesson_details_${lessonId}`
    
    if (isCacheValid(cacheKey)) {
      return getCache(cacheKey)
    }

    const fallbackData = {
      id: lessonId,
      totalQuestions: 20,
      correctAnswers: 0,
      progress: 0,
      vocabulary_count: 0,
      quiz_count: 0
    }

    return handleApiCall(
      cacheKey,
      () => getLessonDetails(lessonId),
      fallbackData
    )
  }

  /**
   * 获取测验进度
   * @param {string} lessonId - 课程ID
   * @param {string} quizType - 测验类型 ('phonetic', 'definition')
   * @returns {Promise<Object>}
   */
  const getQuizProgressData = async (lessonId, quizType) => {
    const cacheKey = `quiz_progress_${lessonId}_${quizType}`
    
    if (isCacheValid(cacheKey)) {
      return getCache(cacheKey)
    }

    const fallbackData = {
      lesson_id: lessonId,
      quiz_type: quizType,
      totalQuestions: 20,
      completedQuestions: 0,
      correctAnswers: 0,
      progress: 0
    }

    return handleApiCall(
      cacheKey,
      () => getQuizProgress(lessonId, quizType),
      fallbackData
    )
  }

  /**
   * 保存测验进度
   * @param {string} lessonId - 课程ID
   * @param {string} quizType - 测验类型
   * @param {Object} progressData - 进度数据
   * @returns {Promise<Object>}
   */
  const saveQuizProgressData = async (lessonId, quizType, progressData) => {
    const cacheKey = `quiz_progress_${lessonId}_${quizType}`
    
    try {
      const response = await saveQuizProgress(lessonId, quizType, progressData)
      
      if (response.code === 0) {
        // 更新缓存
        const updatedData = { ...progressData, lesson_id: lessonId, quiz_type: quizType }
        setCache(cacheKey, updatedData)
        
        // 清除相关的lesson进度缓存，强制重新获取
        clearCache(`lesson_progress_${lessonId}`)
        
        return response.data
      } else {
        throw new Error(response.msg || '保存进度失败')
      }
    } catch (err) {
      console.error(`保存测验进度失败 [${lessonId}/${quizType}]:`, err)
      throw err
    }
  }

  /**
   * 更新阅读进度
   * @param {string} lessonId - 课程ID
   * @param {Object} data - 进度数据
   * @returns {Promise<Object>}
   */
  const updateReadingProgressData = async (lessonId, data) => {
    try {
      const response = await updateReadingProgress(lessonId, data)
      
      if (response.code === 0) {
        // 清除相关缓存
        clearCache(`lesson_progress_${lessonId}`)
        return response.data
      } else {
        throw new Error(response.msg || '更新阅读进度失败')
      }
    } catch (err) {
      console.error(`更新阅读进度失败 [${lessonId}]:`, err)
      throw err
    }
  }

  /**
   * 更新词汇进度
   * @param {string} lessonId - 课程ID
   * @param {Object} data - 进度数据
   * @returns {Promise<Object>}
   */
  const updateVocabularyProgressData = async (lessonId, data) => {
    try {
      const response = await updateVocabularyProgress(lessonId, data)
      
      if (response.code === 0) {
        // 清除相关缓存
        clearCache(`lesson_progress_${lessonId}`)
        return response.data
      } else {
        throw new Error(response.msg || '更新词汇进度失败')
      }
    } catch (err) {
      console.error(`更新词汇进度失败 [${lessonId}]:`, err)
      throw err
    }
  }

  /**
   * 更新文章进度
   * @param {string} lessonId - 课程ID
   * @param {Object} data - 进度数据
   * @returns {Promise<Object>}
   */
  const updateEssayProgressData = async (lessonId, data) => {
    try {
      const response = await updateEssayProgress(lessonId, data)
      
      if (response.code === 0) {
        // 清除相关缓存
        clearCache(`lesson_progress_${lessonId}`)
        return response.data
      } else {
        throw new Error(response.msg || '更新文章进度失败')
      }
    } catch (err) {
      console.error(`更新文章进度失败 [${lessonId}]:`, err)
      throw err
    }
  }

  /**
   * 计算统一进度百分比
   * @param {number} completed - 已完成数量
   * @param {number} total - 总数量
   * @returns {number} 进度百分比 (0-100)
   */
  const calculateProgress = (completed = 0, total = 0) => {
    if (!total || total <= 0) return 0
    return Math.min(100, Math.round((completed / total) * 100))
  }

  /**
   * 格式化进度数据
   * @param {Object} rawData - 原始数据
   * @returns {Object} 格式化后的进度数据
   */
  const formatProgressData = (rawData) => {
    return {
      ...rawData,
      progress: calculateProgress(rawData.completed || rawData.learned_words, rawData.total || rawData.total_words),
      formatted_progress: `${calculateProgress(rawData.completed || rawData.learned_words, rawData.total || rawData.total_words)}%`
    }
  }

  // 计算属性
  const hasError = computed(() => error.value !== null)
  const isReady = computed(() => !isLoading.value && !hasError.value && progressData.value !== null)

  return {
    // 状态
    isLoading,
    error,
    progressData,
    hasError,
    isReady,
    
    // 方法
    getLessonProgressData,
    getLessonDetailsData,
    getQuizProgressData,
    saveQuizProgressData,
    updateReadingProgressData,
    updateVocabularyProgressData,
    updateEssayProgressData,
    calculateProgress,
    formatProgressData,
    
    // 缓存管理
    clearCache,
    clearAllCache,
    isCacheValid,
    
    // 工具方法
    retry: (key, apiCall, fallbackData) => handleApiCall(key, apiCall, fallbackData)
  }
}

/**
 * 全局进度管理实例
 * 用于跨组件共享进度状态
 */
export const globalProgress = useProgress()

/**
 * 进度管理工具函数
 */
export const progressUtils = {
  /**
   * 格式化进度显示
   * @param {number} progress - 进度值 (0-100)
   * @returns {string}
   */
  formatProgress: (progress) => `${Math.round(progress)}%`,
  
  /**
   * 判断是否完成
   * @param {number} progress - 进度值
   * @returns {boolean}
   */
  isCompleted: (progress) => progress >= 100,
  
  /**
   * 获取进度状态
   * @param {number} progress - 进度值
   * @returns {string}
   */
  getProgressStatus: (progress) => {
    if (progress >= 100) return 'completed'
    if (progress >= 50) return 'in-progress'
    if (progress > 0) return 'started'
    return 'not-started'
  },
  
  /**
   * 获取进度颜色
   * @param {number} progress - 进度值
   * @returns {string}
   */
  getProgressColor: (progress) => {
    if (progress >= 100) return '#4CAF50' // 绿色
    if (progress >= 50) return '#2196F3'  // 蓝色
    if (progress > 0) return '#FF9800'    // 橙色
    return '#9E9E9E'                      // 灰色
  }
} 